package com.bwstudio.common.unires.config;

import javax.annotation.Resource;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.bwstudio.common.unires.interceptor.ResponseResultInterceptor;

import lombok.extern.slf4j.Slf4j;

/**
 * @ComponentScan与@ConditionalOnBean同时启用会冲突，导致此@Configuration不生效，原理说明：
 *   当spring.factories注册当前配置文件时，发现ConditionalOnBean中的条件bean不存在
 *   （因为此时@ComponentScan尚未生效而无法扫描到条件bean），导致当前@Configuration文件失效
 *   @author buwei
 */
@Slf4j
@Configuration
@ComponentScan("com.bwstudio.common.unires")
//@ConditionalOnBean({ResponseResultInterceptor.class}) // 当给定的在bean存在时,则实例化当前Bean
@EnableConfigurationProperties(UnifiedResponseProperties.class) // 使使用 @ConfigurationProperties 注解的类生效。
@ConditionalOnProperty(prefix = "unified-response", value = "enabled", havingValue = "true") // @ConditionalOnProperty实现是通过havingValue与配置文件中的值对比,返回为true则配置类生效,反之失效.
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UnifiedResponseInterceptorConfig implements WebMvcConfigurer {

    private final UnifiedResponseProperties unifiedResponseProperties;
    
	private final ResponseResultInterceptor responseResultInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		log.info("---------- 统一响应体拦截器【启用】 ----------");

		/**
		 * 如果配置文件中不设置
		 * unified-response.interceptor-apiuri
		 * 默认拦截全部路径
		 */
		String apiUri = StringUtils.isEmpty(unifiedResponseProperties.getInterceptorApiuri()) ? "/**" : unifiedResponseProperties.getInterceptorApiuri();
		log.info("---------- 拦截的API URL：" + apiUri);
		//响应结果控制拦截
		registry.addInterceptor(responseResultInterceptor).addPathPatterns(apiUri);
	}

}
